<template>
  <div class="upload-wrapper">
    <div class="img-container">
      <!-- <ul class="img-wrapper">
         <li class="img-list" v-for="(item, index) in files" :key="'b' + index">
           <div class="img-item vux-1px" @click="showPreviewer(index)">
             <img class="previewer-img" :src="item.url" :alt="item.attachId">
           </div>
         </li>

         <li class="img-list">
           <div class="img-item" ref="container">
             <a id="selectfiles" class="selectfiles" href="javascript:void(0);" class="vux-1px">
               <i class="iconfont icon-jia"></i>
             </a>
           </div>
         </li>
       </ul>-->
      <ul class="img-wrapper"
          ref="ulWrapper">
        <li class="img-list img-arr vux-1px"
            :class="[androidVersion >= 4.4 ? 'nthChilds' : '']"
            :style="{width:liWidth+'px'}"
            v-for="(item, index) in filesList"
            @click.stop.self="showPreviewer(index)"
            :key="'b' + index">
          <!--X 删除图标处-->
          <div v-if="!isDisabled" class="delete" @click.stop="deleteFile(index)">
            <div class="icon-delete">
              <i class="iconfont icon-iconmianxingshujushanchu">&#xe632;</i>
            </div>
          </div>
          <!--展示图片处-->
          <div class="img-item img-item-bg" ref="imgItemBg">
            <img class="previewer-img" :src="item.url" :alt="item.attachId">
          </div>
        </li>

        <!--
        创建上传动画
        <li class="img-list vux-1px bgImg" id=file.id>
          <div class="img-item pro-modal">
            <span >60 %</span>
          </div>
        </li>
        -->
        <!--上传按钮区-->
        <li v-if="!isFinished && files.length <= 20"
            :style="{width:liWidth+'px'}"
            @click.stop="getAccessToken"
            class="img-list vux-1px" ref="addFile">
          <div class="img-item" ref="container">
            <a ref="selectfiles" class="selectfile" href="javascript:void(0);">
              <i class="iconfont icon-jia">&#xe624;</i>
            </a>
          </div>
        </li>
      </ul>
    </div>
    <!--图片展示区-->

    <previewer :list="filesList" ref="previewer"></previewer>
  </div>
</template>
<script>
  import axios from '../../api/config'
  import plupload from 'plupload'
  import { _getAccessToken, _putFiles, _deleteAttachments } from '../../api/api'
  import { Previewer } from 'vux'
  export default {
    data() {
      return {
        ulWrapper: null,
        uploader: null,

        uploadData: null,
        /*options: {
          getThumbBoundsFn (index) {
            // find thumbnail element
            let thumbnail = document.querySelectorAll('.previewer-img')[index]
            // get window scroll Y
            let pageYScroll = window.pageYOffset || document.documentElement.scrollTop
            // optionally get horizontal scroll
            // get position of element relative to viewport
            let rect = thumbnail.getBoundingClientRect()
            // w = width
            return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}
            // Good guide on how to get element coordinates:
            // http://javascript.info/tutorial/coordinates
          }
        },*/

        h: 96
      }
    },
    components: {
      Previewer
    },
    props: {
      waybillNo: String,
      files: Array,
      groupCode: String,
      isDisabled: Boolean,
      isFinished: Boolean,

      accessTokenObj: Object,

      screenObjs: Object
    },
    computed: {
      w() {
        return parseInt((this.screenObjs.screenWidths - 28 - 18) * 0.31)
      },
      filesList() {
        let arr = []

        if(this.files) {
          this.files.forEach((item, index) => {
            let obj = {}
            obj.url = item.url + `?x-oss-process=image/resize,m_fill,h_${this.h * 2},w_${this.w * 2}`
            obj.src = item.url + `?x-oss-process=image/resize,w_750/auto-orient,0`
            let image = document.createElement('img')
            image.src = obj.src
            image.onload = function () {
              obj.h = image.height
              obj.w = image.width
            }
            arr.push(obj)
          })
        }
        return arr
      },
     /* lastWidth() {
        if(this.screenObjs.androidVersion < 4.4) {
          return this.screenObjs.screenWidths * 1.1
        } else if(this.screenObjs.dprs <= 2) {
          return this.screenObjs.screenWidths * 2
        } else if(this.screenObjs.dprs > 2) {
          return this.screenObjs.screenWidths * 3
        } else {
          return this.screenObjs.screenWidths * 2
        }
      },
      lastHeight() {
        if(this.screenObjs.androidVersion < 4.4) {
          return this.screenObjs.screenHeights * 1.1
        } else if(this.screenObjs.dprs <= 2) {
          return this.screenObjs.screenHeights * 2
        } else if(this.screenObjs.dprs > 2) {
          return this.screenObjs.screenHeights * 3
        } else {
          return this.screenObjs.screenWidths * 2
        }
      },*/
      androidVersion() {
        return this.screenObjs.androidVersion
      },

      /*ulWidth() {
        return this.screenObjs.screenWidths - 28
      },*/
      liWidth() {
        let n
        if(this.androidVersion < 4.4) {
          n = 120
        } else if(this.androidVersion >= 4.4 || this.screenObjs.otherMobile == -1) {
          n = this.w
        }
        return n
        /*if(this.screenObjs.screenWidths < 320) {
          return (this.screenObjs.screenWidths - 28 - 18) * 0.3
        } else {
          return (this.screenObjs.screenWidths - 28 - 18) * 0.31
        }*/

      }
    },
    mounted() {
      this.createUploader()
    },
    methods: {
      get_suffix(filename) { //获取文件格式名
        let pos = filename.lastIndexOf('.')
        let suffix = ''
        if (pos != -1) {
          suffix = filename.substring(pos)
        }
        return suffix
      },
      set_upload_param(up, fileid, filename) {  //设置上传参数

        let _key = this.accessTokenObj.dir + fileid + this.get_suffix(filename)
        this.uploadData = {
          'key': _key,
          'policy': this.accessTokenObj.policy,
          'OSSAccessKeyId': this.accessTokenObj.accessid,
          'success_action_status': '200',
          'signature': this.accessTokenObj.signature
        }

        up.setOption({
          'url': this.accessTokenObj.host,
          'multipart_params': this.uploadData
        })

      },
      createUploader() {
        let that = this

        that.uploader = new plupload.Uploader({
          runtimes: 'html5',
          multi_selection: false,
          browse_button: that.$refs.selectfiles,    //选择文件按钮
          container: that.$refs.container,
          max_file_size : '15mb',
          /*chunk_size: '400kb',*/
          max_retries: 1,
          resize : {

            quality : 76,
            preserve_headers: false
          },
          url: that.accessTokenObj.host,

          init: {

            QueueChanged(up) {
              console.log('上传队列变化了。。')
              up.start()
            },

            FilesAdded(up, files) {         //文件添加时
              that.ulWrapper = that.$refs.ulWrapper
              console.log('文件添加时')
              plupload.each(files, function (file) {
                console.log(file.id)
                let newEle = document.createElement('li')
                newEle.className = 'img-list vux-1px bgImg'
                newEle.style.width= that.liWidth + 'px'
                newEle.id=file.id
                newEle.innerHTML = `<div class="img-item pro-modal">
                                      <span>0 %</span>
                                    </div>`
                that.ulWrapper.insertBefore(newEle, that.$refs.addFile)
              })
            },

            BeforeUpload(up, file) {         //上传之前  确定各参数
              //console.log('上传设置之前:' + that.expire)
              that.set_upload_param(up, file.id, file.name, true)

            },

            UploadProgress(up, file) {          //上传过程中
              console.log('文件上传过程中')
              let newEleId1 = document.getElementById(file.id)
              let pro = newEleId1.getElementsByClassName('pro-modal')[0]
              let spanEle = pro.getElementsByTagName('span')[0]
              spanEle.innerHTML = file.percent + ' %'
            },

            FileUploaded(up, file, res) {         //上传完成后
              if (res.status == 200) {
                console.log('上传成功了')
                /*成功后调取后台服务器接口。*/
                let url = _putFiles(that.waybillNo, that.groupCode)
                let fileName = file.id + that.get_suffix(file.name)
                axios({
                  method: 'put',
                  url: url,
                  data: {
                    fileDir: that.accessTokenObj.dir,
                    fileName: fileName
                  }
                }).then((res) => {
                  if(res.data.meta.code == 'SUCCESS') {
                    let resData = res.data.data
                    //that.$emit('changeFiles', resData)
                    let newEleId2 = document.getElementById(file.id)
                    that.ulWrapper.removeChild(newEleId2)
                    that.files.push(resData)
                    console.log(that.files)
                  }
                }).catch((err) => {
                  console.log(err)
                })
              }
            },

            Error(up, err) {
              console.log(err)
              console.log(11111111)
              that.$vux.toast.show({
                text: '上传失败',
                type: 'warn'
              })
              let newEleUploads = document.getElementsByClassName('bgImg')
              for(let i = newEleUploads.length - 1; i >= 0; i--) {
                that.ulWrapper.removeChild(newEleUploads[i])
              }
            }
          }
        })
        that.uploader.init()
        setTimeout(() => {
          this.uploader.refresh()
        }, 400)
      },


      showPreviewer(index) {
        this.$refs.previewer.show(index)
      },
      deleteFile(index) {
        let attachId = this.files[index].attachId
        let url = _deleteAttachments(this.waybillNo, attachId)
        axios.delete(url)
          .then((res) => {
            if(res.data.meta.code == 'SUCCESS') {
              this.files.splice(index, 1)
            } else {
              this.$vux.toast.show({
                text: res.data.meta.code,
                type: 'warn'
              })
            }
          }).catch((err) => {
          this.$vux.toast.show({
            text: '连接服务器失败',
            type: 'warn'
          })
        })
      },

      /*获取上传图片的令牌*/
      getAccessToken() {
        //let url = _getAccessToken(this.waybillNo)
        let _Now = new Date().getTime() / 1000
        console.log('子组件；。。')
        if(window.sessionStorage.accessToken) {
          let accessTokenObjs = JSON.parse(window.sessionStorage.accessToken)
          console.log(this.accessTokenObj)
          if(_Now + 3 > accessTokenObjs.expire) { //过期了
            console.log('过期了')
            this.$emit('accessToken', 'hello')
          } else {
            console.log('没过期')
            console.log(accessTokenObjs)
          }
        } else {
          console.log('22222')
          this.$emit('accessToken', 'hello')
        }
      }
    }
  }
</script>

<style lang="less" rel="stylesheet/less">
  @import '~vux/src/styles/1px.less';
  @import "../../common/flexBox.less";
  @height: 94px;
  .upload-wrapper {
    .img-container {
      margin-top: 15px;
      .img-wrapper {
        /*.flexBox;

        .flexWrap;*/

        list-style: none;
        .img-list {
          float: left;
          /*position: relative;
          -webkit-flex: 0 0 31.5%; !* Chrome *!
          -ms-flex: 0 0 31.5%; !* IE 10 *!
          flex: 0 0 31.5%; !* NEW, Spec - Opera 12.1, Firefox 20+ *!*/
          height: @height;
          margin-bottom: 9px;
          margin-right: 9px;

          &.img-arr {
            .delete {
              position: absolute;
              z-index: 10;
              right: -9px;
              top: -11px;
              padding: 4px;
              color: #FE5F56;
              .icon-delete {
                .flexBox;

                .flexItems;

                .flexContent;

                width: 18px;
                height: 18px;
                border-radius: 50%;
                background-color: #b3b3b3;
                i {
                  font-style: normal;
                  color: #fff;
                  font-size: 14px;
                }
              }
            }
          }
          &.bgImg {
            background: url("./img/uploadLoading.png") no-repeat;
            /*background: url("http://bucket-ane56.oss-cn-hangzhou.aliyuncs.com/upload-bg.png?x-oss-process=image/resize,w_150/auto-orient,0") no-repeat;*/
            background-size: cover;
          }
          .img-item {
            height: 100%;
            &.img-item-bg {
              background-color: rgba(167, 167, 167, 0.7);
            }
            img {
              width: 100%;
              height: 100%;
            }
          }
          .pro-modal {
            position: absolute;
            .flexBox;

            .flexItems;

            .flexContent;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            span {
              font-size: 18px;
            }
          }
        }
        .nthChilds {
          &:nth-child(3n + 0) {
            margin-right: 0;
          }
        }
        @media screen and (max-width: 320px) {
          .img-list {
            /*-webkit-flex: 0 0 30.3%; !* Chrome *!
            -ms-flex: 0 0 30.3%; !* IE 10 *!
            flex: 0 0 30.3%; !* NEW, Spec - Opera 12.1, Firefox 20+ *!*/
          }
        }
      }
      .img-wrapper:after {
        content: '';
        display: table;
        clear: both;
      }
      .selectfile {
        width: 100%;
        height: 100%;
        .flexBox;

        .flexItems;

        .flexContent;
        .iconfont {
          font-size: 25px;
          color: #bdbaba;
        }
      }
    }
  }
</style>
